
package com.phevos.knowledge.action;

import java.io.BufferedWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.phevos.Phevos;
import com.phevos.common.dbpool.TransactionManager;
import com.phevos.common.dbpool.exception.DBPoolException;
import com.phevos.common.util.SerialException;
import com.phevos.common.util.SerialManager;
import com.phevos.usercenter.client.service.Orgnization;
import com.phevos.usercenter.client.service.WebUtil;
import com.phevos.usercenter.client.vo.UserValue;
import com.phevos.web.db.DAOManager;
import com.phevos.web.db.PageQueryUtil;
import com.phevos.web.db.TopQueryUtil;
import com.phevos.web.util.DAOUtil;
import com.phevos.web.util.DBUtil;
import com.phevos.web.util.DateUtil;
import com.phevos.web.util.DecodeUtil;
import com.phevos.web.util.FileUploadRequest;
import com.phevos.web.util.RequestUtil;

public class CommAction extends DispatchAction
{
    private static Logger logger = LoggerFactory.getLogger(CommAction.class.getName());

    private static final String fatherType = "0";

    public ActionForward mainView(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        String cat_id = RequestUtil.getParameterWhitDefault(request, "cat_id", "0");
        String title = RequestUtil.getParameterWhitDefault(request, "title", "");
        String pageNo = RequestUtil.getParameterWhitDefault(request, "pageNo", "1");
        String sqlWhere = "from tbfzyw_kb_articles where ";
        if (!cat_id.equals("0"))
        {
            sqlWhere += "cat_id=" + cat_id + " and ";
        }
        if (title.length() != 0)
        {
            sqlWhere += "title like '%" + title + "%' and ";
        }
        sqlWhere += "1=1";
        String sql = "select count(*) " + sqlWhere;
        String total = (((Object[])DAOUtil.queryToArrList(sql).get(0))[0]).toString();
        sql = "select * " + sqlWhere + " order by modified desc";
        List result = PageQueryUtil.queryToMapList(sql, 15, Integer.parseInt(pageNo));
        Map typeNames = DAOUtil.queryToMap("select cat_id,cat_name from tbfzyw_categories");
        DecodeUtil.decodeString(result, "cat_id", "typeName", typeNames, "δ֪����");

        List userList = Orgnization.getALlUser();
        HashMap userMap = new HashMap();
        for (int i = 0; userList != null && i < userList.size(); i++)
        {
            UserValue userValue = (UserValue)userList.get(i);
            userMap.put(userValue.getId().intValue() + "", userValue.getName());
        }

        // Map userMap = UserUtil.queryIdAndNameToMap();
        DecodeUtil.decodeString(result, "user_id", "user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeString(result, "modified_user_id", "modified_user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeDate(result, "created", "created", null, "");
        DecodeUtil.decodeDate(result, "modified", "modified", null, "");
        sql = "select cat_id,cat_name from tbfzyw_categories";
        List types = DAOUtil.queryToMapList(sql);
        // ����
        sql = "select * from tbfzyw_kb_articles order by modified desc";
        List newest = TopQueryUtil.queryToMapList(sql, 3);
        DecodeUtil.decodeDate(newest, "modified", "modified", null, "");
        // ����
        sql = "select * from tbfzyw_kb_articles order by views desc";
        List popest = TopQueryUtil.queryToMapList(sql, 3);
        // δ�ش�
        sql = "select * from tbfzyw_kb_questions where published='1'";
        List noanswer = TopQueryUtil.queryToMapList(sql, 5);
        DecodeUtil.decodeDate(noanswer, "creation", "creation", null, "");
        request.setAttribute("cat_id", cat_id);
        request.setAttribute("title", title);
        request.setAttribute("pageNo", pageNo);
        request.setAttribute("perPage", "15");
        request.setAttribute("total", total);
        request.setAttribute("totalPage", "" + (int)Math.ceil(Integer.parseInt(total) / 15.0d));
        request.setAttribute("result", result);
        request.setAttribute("types", types);
        request.setAttribute("newest", newest);
        request.setAttribute("popest", popest);
        request.setAttribute("noanswer", noanswer);
        return mapping.findForward("mainView");
    }

    /**
     * ����ά����ҳ�������action,��������list��jsp
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     */
    public ActionForward mainType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        List<?> types;
        List<HashMap<?, ?>> resultList = new ArrayList<HashMap<?, ?>>();
        
            // ��ѯ cat_parent_name ��δ��ȡ
            types = DAOUtil
                    .queryToMapList("select cat_id,cat_parent,cat_level,cat_name,cat_description from tbfzyw_categories");
            // ����
            for (int i = 0; i < types.size(); i++)
            {
                HashMap tempMap = (HashMap)types.get(i);
                String cat_parent = tempMap.get("cat_parent").toString();
                String cat_id = tempMap.get("cat_id").toString();
                if (cat_parent.equals(fatherType))
                {
                    resultList.add(tempMap);
                    for (int j = 0; j < types.size(); j++)
                    {
                        HashMap temp = (HashMap)types.get(j);
                        String parent = temp.get("cat_parent").toString();
                        if (parent.equals(cat_id))
                        {
                            resultList.add(temp);
                        }
                    }
                }
            }

            // ׼�������ͱ����ַ�
            Map catps = DAOUtil.queryToMap("select cat_id,cat_name from tbfzyw_categories where cat_level=0");
            // ���븸����

            DecodeUtil.decodeString(types, "cat_parent", "cat_parent_name", catps, "û�и�����");
            DecodeUtil.decodeBoolean(types, "cat_level", "has_child", "1");

       
        if(logger.isDebugEnabled())
        {
            logger.debug(""+types);
        }
        
        
        /* �������jsp */
        request.setAttribute("types", resultList);
        request.setAttribute("currentUserId", WebUtil.getCurrentAccount(request));
        return mapping.findForward("mainType");
    }

    /**
     * ɾ��һ�����͵�action
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws Exception
     */
    public ActionForward delType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, Exception
    {

        String cat_id = RequestUtil.getParameterWhitDefault(request, "cat_id", "");
        if (cat_id.equals(""))
        {
            return RequestUtil.forwardErrorMapping(mapping, request, "û�д���Ҫɾ�������.");
        }
        try
        {
            // �������Ƿ����
            String sql = "select count(*) from tbfzyw_categories where cat_id=" + cat_id;
            int ct = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql).get(0))[0])
                    .toString());
            if (ct != 1)
            {
                return RequestUtil.forwardErrorMapping(mapping, request, "Ҫɾ�����Ͳ����ڣ�");
            }

            sql = "select count(*) from tbfzyw_kb_articles where cat_id=" + cat_id;
            int ct1 = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql).get(0))[0])
                    .toString());
            if (ct1 != 0)
            {
                return RequestUtil.forwardErrorMapping(mapping, request, "Ҫɾ�������´������£���ɾ�����º���ɾ�����");
            }
            sql = "select count(*) from tbfzyw_kb_questions where cat_id=" + cat_id;
            int ct2 = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql).get(0))[0])
                    .toString());
            if (ct2 != 0)
            {
                return RequestUtil.forwardErrorMapping(mapping, request, "Ҫɾ�������´������£���ɾ���������ɾ�����ͣ�");
            }
            sql = "select count(*) from tbfzyw_categories where cat_parent=" + cat_id;
            int ct3 = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql).get(0))[0])
                    .toString());
            if (ct3 != 0)
            {
                return RequestUtil.forwardErrorMapping(mapping, request,
                        "Ҫɾ�������´��������ͣ���ɾ�������ͺ���ɾ������ͣ�");
            }

            // ��ʼɾ��
            String sqls[] = new String[1];
            sqls[0] = "delete from tbfzyw_categories where cat_id=" + cat_id;
            // String subsql = " where cat_id ="
            // + cat_id
            // + " or cat_id in( select cat_id from tbfzyw_categories where cat_parent="
            // + cat_id + ")";
            // sqls[0] = "delete from tbfzyw_kb_questions" + subsql;
            // sqls[1] = "delete from tbfzyw_kb_articles" + subsql;
            // sqls[2] = "delete from tbfzyw_categories" + subsql;
            DAOUtil.exeSqls(sqls);
        }
        catch (Exception e)
        {
            throw e;
        }
        return mainType(mapping, form, request, response);
    }

    /**
     * �޸����ͣ��޸ĵ��ֶΣ���ơ�����
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     */
    public ActionForward modType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {

        String cat_id = RequestUtil.getParameterWhitDefault(request, "cat_id", "");
        String cat_name = RequestUtil.getParameterWhitDefault(request, "cat_name", "");
        String cat_description = RequestUtil
                .getParameterWhitDefault(request, "cat_description", "");
        /*try
        {*/
            // �������Ƿ����
            String sql = "select count(*) from tbfzyw_categories where cat_id=" + cat_id;
            int ct = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql).get(0))[0])
                    .toString());
            if (ct != 1)
            {
                return RequestUtil.forwardErrorMapping(mapping, request, "Ҫ�޸ĵ����Ͳ����ڣ�");
            }
            sql = "update tbfzyw_categories set cat_name=" + "'" + cat_name + "',cat_description='"
                    + cat_description + "' where cat_id=" + cat_id;
            DAOUtil.exeSqls(new String[]{sql});
        /*}
        catch (Exception e)
        {
            throw e;
        }*/
        /* �������ģ�� */
        return mainType(mapping, form, request, response);
    }

    /**
     * ���һ���������ӵ����Ϊһ������
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws DBPoolException 
     * @throws SerialException 
     * @throws SQLException 
     */
    public ActionForward addType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException, SerialException, DBPoolException
    {

        String cat_name = RequestUtil.getParameterWhitDefault(request, "cat_name", "");
        String cat_description = RequestUtil
                .getParameterWhitDefault(request, "cat_description", "");
        String cat_parent = RequestUtil.getParameterWhitDefault(request, "cat_parent", "0");
        int cat_level = cat_parent.equals("0") ? 0 : 1;
       /* try
        {*/
            int id = SerialManager.getInstance().getNextId("kb_type_id");
            String sql = "insert into tbfzyw_categories (cat_id, cat_parent, cat_level, cat_name, cat_description) values("
                    + id
                    + ","
                    + cat_parent
                    + ","
                    + cat_level
                    + ",'"
                    + cat_name
                    + "','"
                    + cat_description + "')";
            DAOUtil.exeSqls(new String[]{sql});
     /*   }
        catch (Exception e)
        {
            throw e;
        }*/
        return mainType(mapping, form, request, response);
    }

    /**
     * ����ά�������������
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws Exception
     */
    public ActionForward addSubType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, Exception
    {
        String cat_parent = RequestUtil.getParameterWhitDefault(request, "cat_id", "0");
        String sql = "select cat_name from tbfzyw_categories where cat_id=" + cat_parent;
        String cat_name = (String)((Object[])DAOUtil.queryToArrList(sql).get(0))[0];
        request.setAttribute("cat_parent", new Integer(cat_parent));
        request.setAttribute("cat_parent_name", cat_name);
        return mapping.findForward("subType");
    }

    /**
     * ����ά������ѯ����
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     */
    public ActionForward queryArticle(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        String cat_id = RequestUtil.getParameterWhitDefault(request, "cat_id", "0");
        String title = RequestUtil.getParameterWhitDefault(request, "title", "");
        String pageNo = RequestUtil.getParameterWhitDefault(request, "pageNo", "1");
        String sqlWhere = "from tbfzyw_kb_articles where ";
        if (!cat_id.equals("0"))
        {
            sqlWhere += "cat_id=" + cat_id + " and ";
        }
        if (title.length() != 0)
        {
            sqlWhere += "title like '%" + title + "%' and ";
        }
        sqlWhere += "1=1";
        String sql = "select count(*) " + sqlWhere;
        String total = (((Object[])DAOUtil.queryToArrList(sql).get(0))[0]).toString();
        sql = "select * " + sqlWhere + " order by modified desc ";
        List result = PageQueryUtil.queryToMapList(sql, 15, Integer.parseInt(pageNo));
        Map typeNames = DAOUtil.queryToMap("select cat_id,cat_name from tbfzyw_categories");
        DecodeUtil.decodeString(result, "cat_id", "typeName", typeNames, "δ֪����");
        // Map userMap = UserUtil.queryIdAndNameToMap();
        List userList = Orgnization.getALlUser();
        HashMap userMap = new HashMap();
        for (int i = 0; userList != null && i < userList.size(); i++)
        {
            UserValue userValue = (UserValue)userList.get(i);
            userMap.put(userValue.getId().intValue() + "", userValue.getName());
        }
        DecodeUtil.decodeString(result, "user_id", "user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeString(result, "modified_user_id", "modified_user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeDate(result, "created", "created", null, "");
        DecodeUtil.decodeDate(result, "modified", "modified", null, "");
        sql = "select cat_id,cat_name from tbfzyw_categories";
        List types = DAOUtil.queryToMapList(sql);
        request.setAttribute("cat_id", cat_id);
        request.setAttribute("title", title);
        request.setAttribute("pageNo", pageNo);
        request.setAttribute("perPage", "15");
        request.setAttribute("total", total);
        request.setAttribute("totalPage", "" + (int)Math.ceil(Integer.parseInt(total) / 15.0d));
        request.setAttribute("result", result);
        request.setAttribute("types", types);
        request.setAttribute("currentUserId", WebUtil.getCurrentAccount(request));
        return mapping.findForward("manArticle");
    }

    /**
     * �鿴����
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     * @throws Exception
     */
    public ActionForward viewArticle(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        String art_id = (String)request.getAttribute("art_id");
        if (art_id == null)
        {
            art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        }
        String authorId = "";
        String sqlArticles = "select * from tbfzyw_kb_articles where art_id=" + art_id;
        List art = DAOUtil.queryToMapList(sqlArticles);
        if (art.size() == 1)
        {
            Map map = (Map)art.get(0);
            authorId = (String)map.get("user_id");
        }
        Object[] args = new Object[1];
        args[0] = new Integer(art_id);
        List article = DAOManager.getInstance().query("view-article", args);
        Map typeNames = DAOUtil.queryToMap("select cat_id,cat_name from tbfzyw_categories");
        DecodeUtil.decodeString(article, "cat_id", "typeName", typeNames, "δ֪����");
        // Map userMap = UserUtil.queryIdAndNameToMap();
        List userList = Orgnization.getALlUser();
        HashMap userMap = new HashMap();
        for (int i = 0; userList != null && i < userList.size(); i++)
        {
            UserValue userValue = (UserValue)userList.get(i);
            userMap.put(userValue.getId().intValue() + "", userValue.getName());
        }
        DecodeUtil.decodeString(article, "user_id", "user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeString(article, "modified_user_id", "modified_user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeDate(article, "created", "created", null, "");
        DecodeUtil.decodeDate(article, "modified", "modified", null, "");
        String sql = "select keyword from tbfzyw_kb_search where art_id=" + art_id;
        List keyList = DAOUtil.queryToArrList(sql);
        String keyword = "";
        for (int i = 0; keyList != null && i < keyList.size(); i++)
        {
            keyword += (String)((Object[])keyList.get(i))[0] + " ";
        }
        sql = "select * from tbfzyw_kb_comment where art_id=" + art_id + " order by entered desc";
        List comments = DAOUtil.queryToMapList(sql);
        DecodeUtil.decodeString(comments, "user_id", "user_name", userMap, "δ֪�û�");
        DecodeUtil.decodeDate(comments, "entered", "entered", null, "");
        sql = "select * from tbfzyw_kb_files where art_id=" + art_id;
        List files = DAOUtil.queryToMapList(sql);
        DecodeUtil.decodeUploadFileName(files, "art_file", "file_name");
        sql = "select * from tbfzyw_kb_urls where art_id=" + art_id;
        List links = DAOUtil.queryToMapList(sql);
        // ��������1
        sql = "update tbfzyw_kb_articles set views=views+1 where art_id=" + art_id;
        DAOUtil.exeSqls(new String[]{sql});
        request.setAttribute("article", article);
        request.setAttribute("keyword", keyword);
        request.setAttribute("comments", comments);
        request.setAttribute("files", files);
        request.setAttribute("links", links);
        request.setAttribute("authorId", authorId);
        // request.setAttribute("currentUserId", UserUtil.getCurrentUserId(request))
        // **************************************************************************************************************************
        request.setAttribute("currentUserId", WebUtil.getCurrentUserId(request));
        return mapping.findForward("viewArticle");
    }

    /**
     * �������
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     * @throws DBPoolException 
     * @throws SerialException 
     */
    public ActionForward addComment(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException, SerialException, DBPoolException
    {
        String comments = RequestUtil.getParameterWhitDefault(request, "comments", "");
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        if (comments.length() != 0 && !art_id.equals("0"))
        {
            // String user_id = UserUtil.getCurrentUserId(request);
            String user_id = WebUtil.getCurrentUserId(request);
            int id = SerialManager.getInstance().getNextId("kb_comment_id");
            StringBuffer sql = new StringBuffer();
            sql.append("insert into tbfzyw_kb_comment values(");
            sql.append(id).append(',');
            sql.append("'").append(user_id).append("',");
            sql.append("'").append(comments).append("',");
            sql.append(DateUtil.toDateSql(new Date()));
            sql.append(',').append(art_id).append(',').append("'1'");
            sql.append(')');
            DAOUtil.exeSqls(new String[]{sql.toString()});
        }
        return viewArticle(mapping, form, request, response);
    }

    /**
     * ���l��
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     * @throws NumberFormatException 
     */
    public ActionForward addLink(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, NumberFormatException, SQLException
    {
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String url = RequestUtil.getParameterWhitDefault(request, "url", "");
        String title = RequestUtil.getParameterWhitDefault(request, "title", "");
        if (title == null)
            title = "";
        StringBuffer sql = new StringBuffer();
        sql.append("select count(*) from tbfzyw_kb_urls where art_id=");
        sql.append(art_id).append(" and art_url='");
        sql.append(url).append("'");
        int ct = Integer.parseInt((((Object[])DAOUtil.queryToArrList(sql.toString()).get(0))[0])
                .toString());
        if (ct == 0 && !art_id.equals("0") && url.length() != 0)
        {
            sql = new StringBuffer();
            sql.append("insert into tbfzyw_kb_urls values(");
            sql.append(art_id).append(",'");
            sql.append(url).append("','");
            sql.append(title).append("')");
            DAOUtil.exeSqls(new String[]{sql.toString()});
        }
        return viewArticle(mapping, form, request, response);
    }

    /**
     * ɾ��l��
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws Exception
     */
    public ActionForward delLink(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, Exception
    {
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String url = RequestUtil.getParameterWhitDefault(request, "url", "");

        // modify by chenguang
        byte[] urlByte = url.getBytes("ISO8859_1");
        String urlChinese = new String(urlByte, "GB2312");

        StringBuffer sql = new StringBuffer();
        sql.append("delete from tbfzyw_kb_urls where art_id=");
        sql.append(art_id).append(" and art_url='");
        sql.append(urlChinese).append("'");
        DAOUtil.exeSqls(new String[]{sql.toString()});
        return viewArticle(mapping, form, request, response);
    }

    /**
     * �ϴ�����
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws Exception
     */
    public ActionForward uploadFile(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, Exception
    {
        FileUploadRequest uploadRequest = new FileUploadRequest(request);
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String comments = uploadRequest.getParameter("file_title");
        List list = uploadRequest.uploads();
        if (!uploadRequest.hasPutInFile("file"))
        {
            throw new Exception("δ�����ϴ��ļ���");
        }
        for (int i = 0; list != null && i < list.size(); i++)
        {
            String[] arr = (String[])list.get(i);
            int acce_id = Integer.parseInt(arr[0]);
            String name = arr[1];
            StringBuffer sql = new StringBuffer();
            sql.append("insert into tbfzyw_kb_files values(");
            sql.append(art_id).append(",").append(acce_id).append(",'");
            sql.append(name).append("','");
            sql.append(comments).append("')");
            DAOUtil.exeSqls(new String[]{sql.toString()});
        }
        return viewArticle(mapping, form, request, response);
    }

    /**
     * ɾ���
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     */
    public ActionForward delAcceFile(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String acce_id = RequestUtil.getParameterWhitDefault(request, "acce_id", "0");
        String sql = "delete from tbfzyw_kb_files where art_id=" + art_id;
        sql += " and acce_id=" + acce_id;
        DAOUtil.exeSqls(new String[]{sql});
        return viewArticle(mapping, form, request, response);
    }

    /**
     * ɾ������
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     * @throws Exception
     */
    public ActionForward delArticle(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException
    {
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String sql = "delete from tbfzyw_kb_articles where art_id=" + art_id;
        DAOUtil.exeSqls(new String[]{sql});
        return queryArticle(mapping, form, request, response);
    }

    /**
     * �༭����
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws Exception
     */
    public ActionForward editArticle(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, Exception
    {
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        Object[] params = new Object[1];
        params[0] = new Integer(art_id);
        List article = DAOManager.getInstance().query("view-article", params);
        String sql = "select cat_id,cat_name from tbfzyw_categories";
        List types = DAOUtil.queryToMapList(sql);
        sql = "select keyword from tbfzyw_kb_search where art_id=" + art_id;
        List keyList = DAOUtil.queryToArrList(sql);
        String keyword = "";
        for (int i = 0; keyList != null && i < keyList.size(); i++)
        {
            keyword += (String)((Object[])keyList.get(i))[0] + " ";
        }
        request.setAttribute("article", article);
        request.setAttribute("types", types);
        request.setAttribute("keyword", keyword);
        return mapping.findForward("editArticle");
    }

    /**
     * ��������
     * 
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws IOException
     * @throws ServletException
     * @throws SQLException 
     * @throws DBPoolException 
     * @throws SerialException 
     */
    public ActionForward saveArticle(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException, SQLException, SerialException, DBPoolException
    {
        String question_id = RequestUtil.getParameterWhitDefault(request, "question_id", "0");
        String art_id = RequestUtil.getParameterWhitDefault(request, "art_id", "0");
        String title = RequestUtil.getParameterWhitDefault(request, "title", "�ޱ���");
        String topic = RequestUtil.getParameterWhitDefault(request, "topic", "������");
        String typeid = RequestUtil.getParameterWhitDefault(request, "typeid", "");
        String keywords = RequestUtil.getParameterWhitDefault(request, "keywords", "");
        String text = RequestUtil.getParameterWhitDefault(request, "text", "");
        StringBuffer sqlBuff = new StringBuffer();

        String user_id = WebUtil.getCurrentUserId(request);
        // String user_id = UserUtil.getCurrentUserId(request);
        if (question_id.length() == 0)
        {
            question_id = "0";
        }
        
        if (art_id.length() == 0 || art_id.equals("0"))
        {
            art_id = "" + SerialManager.getInstance().getNextId("kb_art_id");
            sqlBuff.append("insert into tbfzyw_kb_articles" +
            		"(art_id,q_id,title,topic,cat_id,user_id,created,modified," +
            		"modified_user_id,published,views,votes_1,votes_2,votes_3,votes_4,votes_5) values(");
            sqlBuff.append(art_id).append(",");
            sqlBuff.append(question_id).append(",'");
            sqlBuff.append(title).append("','");
            sqlBuff.append(topic).append("',");
            sqlBuff.append(typeid).append(",'");
            sqlBuff.append(user_id).append("',");
            sqlBuff.append(DateUtil.toDateSql(new java.util.Date()));
            sqlBuff.append(",");
            sqlBuff.append(DateUtil.toDateSql(new java.util.Date()));
            sqlBuff.append(",'").append(user_id);
            sqlBuff.append("','").append(0);
            sqlBuff.append("',").append(0);
            sqlBuff.append(",").append(0);
            sqlBuff.append(",").append(0);
            sqlBuff.append(",").append(0);
            sqlBuff.append(",").append(0);
            sqlBuff.append(",").append(0);
            sqlBuff.append(")");
        }
        else
        {
            sqlBuff.append("update tbfzyw_kb_articles set title='");
            sqlBuff.append(title).append("',topic='");
            sqlBuff.append(topic).append("',cat_id=");
            sqlBuff.append(typeid).append(",modified_user_id='");
            sqlBuff.append(user_id).append("',modified=");
            sqlBuff.append(DateUtil.toDateSql(new java.util.Date()));
            sqlBuff.append(" where art_id=").append(art_id);
        }
        String[] keys = keywords.split(" ");
        int size = 2;
        for (int i = 0; i < keys.length; i++)
        {
            if (keys[i].length() != 0)
            {
                size++;
            }
        }
        if (!question_id.equals("0"))
        {
            size += 1;
        }
        String[] sqls = new String[size];
        sqls[0] = sqlBuff.toString();
        sqls[1] = "delete from tbfzyw_kb_search where art_id=" + art_id;
        int index = 2;
        for (int i = 0; i < keys.length; i++)
        {
            if (keys[i].length() != 0)
            {
                sqls[index++] = "insert into tbfzyw_kb_search(art_id,keyword,score) values(" + art_id
                        + ",'" + keys[i] + "',"+"0)";
            }
        }
        if (!question_id.equals("0"))
        {
            sqls[size - 1] = "update tbfzyw_kb_questions set published='3' where question_id="
                    + question_id;
        }
        //�����mysql�Ļ�����ֱ�������ط�insert��
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        TransactionManager transMgr = null;
        if(Phevos.DATABASE_MYSQL==Phevos.getDataBaseType())
        {
            try{
                logger.debug("text is{}",text);
                logger.debug("art_id is{}",art_id);
            String textsql = "update tbfzyw_kb_articles set text = ? where art_id=?";
          
            BufferedWriter out = null;
           
            transMgr = new TransactionManager();
            transMgr.beginTransaction();
            conn = transMgr.getConnection();
            stmt = conn.prepareStatement(textsql);
            stmt.setString(1, text);
            stmt.setString(2, art_id);
            stmt.execute();
            transMgr.commit();
            }catch(Exception e)
            {             
                transMgr.cancelTransaction();
                logger.error("xxxx",e);
            }finally
            {
                DBUtil.closeResultSet(rs);
                DBUtil.closeStatement(stmt);
                transMgr.endTransaction();
            }
            
            
        }
        
        else if(Phevos.DATABASE_ORACLE==Phevos.getDataBaseType())
        {
            Object[] args = new Object[3];
            args[0] = "text";
            args[1] = text;
            args[2] = new Integer(art_id);
            DAOUtil.exeSqls(sqls);
            DAOManager.getInstance().query("text-article", args);
        }
       
        request.setAttribute("art_id", art_id);
        return viewArticle(mapping, form, request, response);
    }
}
